#!/usr/bin/env python3.7.9
'''
Copyright © 2021 DUE TUL
@ date  : Monday january 15, 2020
@ desc  : This modules is used to analysis noise reduction 
@ author:  
'''
import wave
import pyaudio
import librosa
import random
import librosa.display
import numpy as np
from pydub import AudioSegment
import matplotlib.pyplot as plt

''' 降噪分析-去除分贝比较大的声音 '''
def read_wav(wavfile, plots=True, normal=False):
    f = wavfile
    params = f.getparams()
    # print(params)
    nchannels, sampwidth, framerate, nframes = params[:4]
    strData = f.readframes(nframes)  # 读取音频，字符串格式
    waveData = np.frombuffer(strData, dtype=np.int16)  # 将字符串转化为int
    waveData = waveData*1.0
    print(waveData.shape)
    waveData[abs(waveData) > 300 ] = 0
    # wave幅值归一化
    if normal == True:
        waveData = waveData*1.0/(max(abs(waveData)))
        waveData[abs(waveData) > 0.1] =  0
    # 绘图
    if plots == True:
        time = np.arange(0, nframes)*(1.0 / framerate)
        plt.figure(dpi=100)
        plt.plot(time, waveData)
        plt.xlabel("Time")
        plt.ylabel("Amplitude")
        plt.title("Single channel wavedata")
        plt.show()
    return (waveData, time)


f = wave.open('3.wav', 'rb')
waveData, time = read_wav(f)